import { useCallback, useRef, useState } from "react"
import { deviceId, dpw12, dpw14, dpw22, dpw4, dpw6, PHONE_REG } from "../../constants"
import { useSetInterval } from "../../hooks"
import { sendMobileCode } from "../../services"
import { observer } from "mobx-react-lite"
import { useGlobalStore } from "../../mobx"
import { StyleSheet, TouchableOpacity, Text } from "react-native"
import { getColorStr } from "../../themes"
import { t } from "../../utils"

const CodeCountDown = ({ mobile }: any) => {
    const { theme, language, changeToastKey } = useGlobalStore()
    const [time, setTime] = useState<number | null>(null)
    const isSendRef = useRef(false)
    
    const countDown = useCallback(() => {
        setTime((t) => {
            if (typeof t === 'number' && t > 0) {
                return t - 1
            }
            isSendRef.current = false
            return null
        })
    },[])
    
    useSetInterval(countDown, typeof time === 'number' ? 1000 : 0)
    
    // 发送验证码
    const sendCode = () => {
        if (isSendRef.current) return
        if (!mobile) {
            changeToastKey('enterMobile')
            return
        }
        if (!PHONE_REG.test(mobile)) {
            changeToastKey('please_enter_correct_phone')
            return
        }
        isSendRef.current = true
        if (mobile) {
            sendMobileCode({
                Mobile: mobile,
                Mac: deviceId,
                SendType: 1
            }).then(() => {
                changeToastKey('codeSucsess')
                setTime(59)
            }).catch(() => {
                isSendRef.current = false
            })
        }
    }
    
    return (
        <TouchableOpacity onPress={sendCode}>
            <Text
                style={{
                    ...styles.btn,
                    backgroundColor: getColorStr(theme, typeof time === 'number' ? 'color_40' : 'color_1'),
                    color: getColorStr(theme, typeof time === 'number' ? 'color_4' : 'color_2')
                }}
            >
                {typeof time === 'number' ? <Text style={{color: getColorStr(theme, 'color_1')}}>{time}s</Text> : null}
                {t(language, typeof time !== 'number' ? 'get_code' : 'resend')}
            </Text>
        </TouchableOpacity>
    )
}

export default observer(CodeCountDown)

const styles = StyleSheet.create({
    btn: {
        fontSize: dpw14,
        lineHeight: dpw22,
        textAlign: 'center',
        paddingHorizontal: dpw12,
        paddingVertical: dpw6,
        marginLeft: dpw12,
        borderRadius: dpw4
    }
})